////
//
/// \file   ./src/label_node.cpp
//
//  Copyright 2007 Chandler Carruth
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations
//  under the License.
//
////

#include <inc/parser/label_node.hpp>

#include <cassert>
#include <string>

#include <boost/regex.hpp>

namespace inc {
namespace parser {

using std::string;
using boost::regex;
using boost::match_results;

//  We have to filter these results for any matches which form a reserved word.
//  FIXME: This is an ugly, and grotesque HACK! We are hard coding the reserved
//  words here, and embedding them in a switch. I have a hard time expressing
//  how ugly this is. This is what I should do, but I don't have time to do
//  currently:
//
//  1) Provide a static registry in the label node where other parse nodes are
//  able to readily add their reserved labels (NB: This is not all
//  word-tokens!! Only word tokens which occur in a potential label context!)
//  with this parser.
//
//  2) Provide static construction of the regular expression (DUH) and
//  construct it _including_ the ability to recognize and disregard any
//  registered reserved words. This should still maintain linear complexity due
//  to the lovely nature of regular languages, and their ability to be
//  expressed as state machines.
const regex LabelNode::label_regex( "(?!begin|end|if|then|else|"
                                    "loop|pre|post|break|broken|finish|finished|"
                                    "scope)"
                                    "_*[a-zA-Z][a-zA-Z0-9_]*" );

/// \brief  Parse text into this label node
/// \author Chandler Carruth
/// \date   2007.06.19
///
/// This builds a label object by parsing out the pattern from the
/// text.

bool
LabelNode::parse( const iterator& first,
                  const iterator& last,
                  iterator& last_parsed )
{
  assert( get_text().empty() && "Tried to parse a node more than once!" );

  match_results<iterator> m;
  if( regex_search( first, last, m, label_regex, boost::match_continuous ) )
  {
    set_text( m.str() );
    last_parsed = m.suffix().first;
    return true;
  }

  last_parsed = first;
  return false;
}

} //  end parser namespace
} //  end inc namespace
